<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="rowShow">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedCate"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
            clearable
          >
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled='allowOrNot' @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table
            :data="manyTableData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 循环渲染Tag标签 -->
              <template v-slot='scope'>
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close='handleClose(i,scope.row)'
                >
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class='input-new-tag'
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column 
            type="index"
            label="#"
            >
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            >
            </el-table-column>
            <el-table-column
              label="操作"
            >
              <template v-slot='scope'>
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="getParamsById(scope.row)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled='allowOrNot' @click="addDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table
            :data="onlyTableData"
            border
            stripe
          >
            <!-- 展开行 -->
            <el-table-column type="expand">
              <!-- 循环渲染Tag标签 -->
              <template v-slot='scope'>
                <el-tag
                  v-for="(item,i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close='handleClose(i,scope.row)'
                >
                  {{item}}
                </el-tag>
                <!-- 输入文本框 -->
                <el-input
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                  class='input-new-tag'
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column 
            type="index"
            label="#"
            >
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            >
            </el-table-column>
            <el-table-column
              label="操作"
            >
              <template v-slot='scope'>
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="getParamsById(scope.row)">修改</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加'+ titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close='addFormDialogClosed'
    >
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="addParams">确 定</el-button>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改'+ titleText"
      :visible.sync="setDialogVisible"
      width="50%"
    >
      <el-form ref="setFormRef" :model="setForm" label-width="80px" :rules="addFormRules" >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="setForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="setDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="setParams">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'Params',
    data(){
      return {
        // 商品分类列表
        cateList:[],
        // 级联选择框选中的分类的ID
        selectedCate:[],
        // 级联选择框配置对象
        cateProps:{ 
          expandTrigger: 'hover',
          value:'cat_id', 
          label:'cat_name',
          children:'children',
        },
        // 当前选中哪一个tab
        activeName:'many',
        // 动态参数的数据
        manyTableData:[],
        // 静态属性的数据
        onlyTableData:[],
        // 添加参数对话框的显示与隐藏
        addDialogVisible:false,
        // 修改参数对话框的显示与隐藏
        setDialogVisible:false,
        // 添加参数的表单数据对象
        addForm:{
          attr_name:'',
        },
        setForm:{
          attr_name:'',
        },
        // 表单验证规则
        addFormRules:{
           attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ],
        }

      }
    },
    computed:{
      // 是否禁用添加参数和属性按钮
      allowOrNot(){
        if(this.selectedCate.length !== 3){
          return true
        }
        return false
      },
      cateId(){
        if(this.selectedCate.length === 3){
          return this.selectedCate[2]
        }
        return null
      },
      titleText(){
        return this.activeName === 'many' ? '动态参数' : '静态属性'
      }
    },
    methods:{
      // 获取级联选择框数据
      async getCateList(){
        const {data: res} = await this.$http.get('categories')
        // console.log(res.data)
        this.cateList = res.data
      },

      // 级联选择框选中项变化，会触发这个函数
      async handleChange(){
        // console.log(this.selectedCate)
        this.getParamsData()
        
      },

      // tab页签点击事件处理函数
      handleTabClick(){
        // console.log(this.activeName)
        this.getParamsData()
      },  

      // 获取级联选择框选中分类的对应属性参数
      async getParamsData(){
        // 证明选中的不是三级分类
        if(this.selectedCate.length !== 3){
          this.selectedCate = []
          this.manyTableData = []
          this.onlyTableData = []
          return 
        }
        // 根据选中的分类的Id，和当前所处的面板，获取对应的参数
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:this.activeName}})
        // console.log(res.data)
        res.data.forEach(item =>{
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值
          item.inputValue = ''
        })
        console.log(res.data)
        if(res.meta.status !== 200){
         return this.$message.error('获取该商品分类的动态参数失败')
        }
        this.activeName === 'many' ? this.manyTableData = res.data : this.onlyTableData = res.data
      },

      // 监听添加对话框的关闭事件
      addFormDialogClosed(){
        this.$refs.addFormRef.resetFields()
      },

      // 添加动态参数或静态属性
      addParams(){
        this.$refs.addFormRef.validate(async valid =>{
          if(!valid) return
          const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,{attr_name:this.addForm.attr_name,attr_sel:this.activeName})
          if(res.meta.status !== 201) this.$message.error('添加失败')
          console.log(res)
          this.$message.success('添加成功')
          this.addDialogVisible = false
          this.getParamsData()
        })
      },

      // 点击按钮，展示修改属性的对话框，并获取对应的属性值显示在输入框中
      async getParamsById(row){
        console.log(row)
        const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes/${row.attr_id}`,{params:{attr_sel:this.activeName}})
        if(res.meta.status !== 200){
          return this.$message.error('获取失败')
        }
        // console.log(res)
        this.setForm = res.data
        this.setDialogVisible=true
      },

      // 点击确定按钮，修改参数
      setParams(){
        this.$refs.setFormRef.validate(async valid =>{
          if(!valid) return
          const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.setForm.attr_id}`,{attr_name:this.setForm.attr_name,attr_sel:this.activeName})
          if(res.meta.status !== 200){
            return this.$message.error('修改失败')
          }
          this.$message.success('修改成功')
          // console.log(res,'####')
          this.setDialogVisible = false
          this.getParamsData()
        })
      },

      // 点击删除按钮，删除该行数据
      async delParams(row){
        const confirmResult = await this.$confirm('此操作将永久删除该数据, 是否继续?', '提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmResult !== 'confirm') return this.$message('取消删除')
        const {data: res} = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if(res.meta.status !== 200){
            return this.$message.error('删除失败')
          }
        this.$message.success('删除成功')
        this.getParamsData()
      },

      // 点击按钮，显示文本输入框
      showInput(row){
        row.inputVisible = true
        // 让文本框自动获得焦点
        // $nextTick的作用，就是当页面上元素被重新渲染之后，才会执行回调函数中的代码
        this.$nextTick(_ =>{
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      // 文本框失去焦点或者按下enter都会触发
      handleInputConfirm(row){
        // console.log('ok')
        if(row.inputValue.trim().length === 0){
          row.inputValue = ''
          row.inputVisible = false
          return 
        } 
        // 如果输入的内容合法，则进行下列操作
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        // 需要发起请求，保存这次操作产生的数据
        this.saveAttrValues(row)
      },

      // 将对attr_vals的操作，保存到数据库
      async saveAttrValues(row){
        const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')})
        if(res.meta.status !== 200){
          return this.$message.error('提交失败')
        }
        this.$message.success('提交成功')
      },
      // 处理标签关闭事件
      handleClose(i,row){
        row.attr_vals.splice(i,1)
        this.saveAttrValues(row)
      }
    },
    created(){
      this.getCateList()
    }
}
</script>

<style scoped>
  .rowShow {
    margin: 15px 0;
  }
.el-cascader {
    width: 20%;
}
.input-new-tag{
  width: 120px;
}
</style>